package cn.yotta.user.core.server.configuration;

import cn.yotta.user.core.server.iface.common.CaptchaGenerator;
import cn.yotta.user.core.server.iface.common.CaptchaStorageStrategy;
import cn.yotta.user.core.server.iface.common.impl.DefaultCaptchaGenerator;
import cn.yotta.user.core.server.iface.common.impl.InMemoryCaptchaStorageStrategy;
import cn.yotta.user.core.server.iface.common.impl.RedisCaptchaStorageStrategy;
import cn.yotta.user.core.server.properties.CaptchaProperties;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static com.google.code.kaptcha.Constants.*;

/**
 * @author wyaoyao
 * @date 2022/11/9 10:22
 */
@Configuration
@EnableConfigurationProperties({CaptchaProperties.class})
public class CaptchaAutoConfiguration {

    @Bean
    public DefaultKaptcha defaultKaptcha(CaptchaProperties captchaProperties) {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 文字验证实现
        properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.google.code.kaptcha.text.impl.DefaultTextCreator");
        // 验证码长度
        properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, captchaProperties.getCaptchaLength().toString());
        properties.setProperty(KAPTCHA_IMAGE_HEIGHT, captchaProperties.getImageWidth().toString());
        properties.setProperty(KAPTCHA_IMAGE_WIDTH, captchaProperties.getImageHeight().toString());
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }

    @Bean
    @ConditionalOnMissingBean(CaptchaGenerator.class)
    public CaptchaGenerator defaultCaptchaGenerator(DefaultKaptcha defaultKaptcha, CaptchaProperties captchaProperties) {
        return new DefaultCaptchaGenerator(defaultKaptcha, captchaProperties.getExpireTime());
    }


    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    public CaptchaStorageStrategy redisCaptchaStorageStrategy(StringRedisTemplate redisTemplate) {
        return new RedisCaptchaStorageStrategy(redisTemplate);
    }

    @Bean
    @ConditionalOnMissingBean(CaptchaStorageStrategy.class)
    public CaptchaStorageStrategy inMemoryCaptchaStorageStrategy(CaptchaProperties captchaProperties) {
        return new InMemoryCaptchaStorageStrategy(captchaProperties.getExpireTime(), TimeUnit.SECONDS);
    }


}
